package com.jx.demo.controller;

import com.jx.demo.service.MessageSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
public class HelloController {

    private final AtomicInteger count = new AtomicInteger(0);

    @Autowired
    private MessageSender messageSender;

    private static final Logger logger = LoggerFactory.getLogger(HelloController.class);

    @RequestMapping("/hello")
    public Map<String, Object> hello() {
        Map<String, Object> map = new HashMap<>(16);
        map.put("now Time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        int[] ints=new int[1024*1024];
        count.addAndGet(1);
//        logger.info("程序开始执行");
//        logger.debug("调试信息：{}", "some-debug-value");
//        logger.warn("警告：{}", "something unusual");
//        logger.error("错误：{}", new RuntimeException("出错了"));
        return map;
    }

    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public ResponseBodyEmitter streamLogs(){
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
        // 开启异步线程处理数据并发送
        new Thread(() -> {
            try {
                while (true) {
                    String logEntry = getLatestLogEntry();
                    if (logEntry != null) {
                        emitter.send(logEntry);
                    }
                    // 每秒检查一次日志更新
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                // 出现异常时结束响应并传递错误信息
                emitter.completeWithError(e);
            }
        }).start();

        return emitter;
    }

    private String getLatestLogEntry() {
        // 模拟从日志文件中获取最新日志条目
        return"2025-02-12 12:00:00 - INFO: User logged in successfully. \n";
    }

    @RequestMapping("/test")
    public int test(){
        return 10/1;
    }


    @GetMapping("/send")
    public String send(@RequestParam("msg") String msg) {
        messageSender.send(msg);
        return "Message sent: " + msg;
    }

}
